﻿using Avalonia.Controls;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using MsBox.Avalonia.Enums;
using OpenQA.Selenium.DevTools.V126.Page;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 畜牧业审核程序国产.Models;
using 畜牧业审核程序国产.Models.ToolsClass;

namespace 畜牧业审核程序国产.ViewModels
{
    internal partial class UserInformationViewModel : ViewModelBase
    {
        Window _thisWindow = null;
        public UserInformationViewModel()
        {
            _settingManager = new SettingManager();
            InitiazeAcountInfo();
            this.IntChooseYear = Global.IntYearNow;
            this.IntChooseSeason = Global.IntSeasonNow;
            this.GetNationDataCommand = new RelayCommand(async () => await ExecuteGetDataFromNation());
            this.GetA406DataCommand = new RelayCommand(async () => await ExecuteGetA406Data());
            this.GetStatsCloudDataCommand = new RelayCommand(async () => await ExecuteGetDataFromStatsCloud());
            WeakReferenceMessenger.Default.Register<TransmitView>(this, OnWindowReceived);
        }

        private void OnWindowReceived(object recipient, TransmitView transmitView)
        {
            if (transmitView != null)
            {
                _thisWindow = transmitView.TransmitedWindow;
            }
        }


        #region 账号密码属性
        private string _str国网账号;

        public string Str国网账号
        {
            get { return _str国网账号; }
            set
            {
                SetProperty(ref _str国网账号, value);

            }
        }

        [ObservableProperty] private string _str国网密码;
        [ObservableProperty] private string _str省网账号;
        [ObservableProperty] private string _str省网密码;
        [ObservableProperty] private string _str统计云账号;
        [ObservableProperty] private string _str统计云密码;
        #endregion
        #region 保存用户名和密码要用到的settingManager
        private SettingManager _settingManager;
        private void InitiazeAcountInfo()
        {
            this.Str国网账号 = _settingManager.Str国网Account;
            this.Str国网密码 = _settingManager.Str国网Password;
            this.Str省网账号 = _settingManager.Str省网Account;
            this.Str省网密码 = _settingManager.Str省网Password;
            this.Str统计云账号 = _settingManager.StrCloudAccount;
            this.Str统计云密码 = _settingManager.StrCloudPassword;

        }
        #endregion
        #region 绑定到view的collection

        private ObservableCollection<int> _clnOfRecentlyThreeYears =
            new() { DateTime.Now.Year - 2, DateTime.Now.Year - 1, DateTime.Now.Year };

        public ObservableCollection<int> ClnOfRecentlyThreeYears
        {
            get => _clnOfRecentlyThreeYears;
            set => SetProperty(ref _clnOfRecentlyThreeYears, value);
        }

        private ObservableCollection<int> _clnOfSeasons = new() { 1, 2, 3, 4 };

        public ObservableCollection<int> ClnOfSeasons
        {
            get => _clnOfSeasons;
            set => SetProperty(ref _clnOfSeasons, value);
        }
        [ObservableProperty]
        private int _intChooseYear;
        [ObservableProperty]
        private int _intChooseSeason;
        [ObservableProperty]
        private string _textSchedule;
        #endregion
        #region  一套表和统计云根据季度，其是否可用的布尔属性
        private bool _isGetDataFromOldEnableNow;
        public bool IsGetDataFromOldEnableNow
        {
            get
            {
                return _isGetDataFromOldEnableNow;
            }
            set => SetProperty(ref _isGetDataFromOldEnableNow, value);
        }
        private bool _isGetDataFromOldEnablePre;
        public bool IsGetDataFromOldEnablePre
        {
            get
            {
                return _isGetDataFromOldEnablePre;
            }
            set => SetProperty(ref _isGetDataFromOldEnablePre, value);
        }
        private bool _isGetDataFromOldEnableYOY;
        public bool IsGetDataFromOldEnableYOY
        {
            get
            {
                return _isGetDataFromOldEnableYOY;
            }
            set => SetProperty(ref _isGetDataFromOldEnableYOY, value);
        }
        private bool _isGetDataFromCloudStatsEnableNow;
        public bool IsGetDataFromCloudStatsEnableNow
        {
            get
            {
                return _isGetDataFromCloudStatsEnableNow;
            }
            set => SetProperty(ref _isGetDataFromCloudStatsEnableNow, value);
        }
        private bool _isGetDataFromCloudStatsEnablePre;
        public bool IsGetDataFromCloudStatsEnablePre
        {
            get
            {
                return _isGetDataFromCloudStatsEnablePre;
            }
            set => SetProperty(ref _isGetDataFromCloudStatsEnablePre, value);
        }
        private bool _isGetDataFromCloudStatsEnableYOY;
        public bool IsGetDataFromCloudStatsEnableYOY
        {
            get
            {
                return _isGetDataFromCloudStatsEnableYOY;
            }
            set => SetProperty(ref _isGetDataFromCloudStatsEnableYOY, value);
        }
        #endregion

        public RelayCommand GetNationDataCommand { get;private set; }
        public RelayCommand GetA406DataCommand { get; private set; }
        public RelayCommand GetStatsCloudDataCommand { get; private set; }


        private async Task ExecuteGetDataFromNation()
        {
            try{
            StaticLogger.SystemInfo("执行从国网一套表下载数据操作");
            MyDataFolderOperator.CreateOrResetDownloadFolder();
            
            Dictionary<int,int> downYearAndSeason = new Dictionary<int, int>
            {
                { IntChooseYear, IntChooseSeason }
            };
            bool isGetDataFromNationSuccess = await 网络操作.Get国网数据(this.Str国网账号, this.Str国网密码, downYearAndSeason, MyDataFolderOperator.DownloadFolderPathInAuditProgramFolder);
            if (!isGetDataFromNationSuccess)
            {
                this.TextSchedule = string.Empty;
                this.TextSchedule = $"数据下载出现错误,请重试!" + Environment.NewLine;
                return;
            }
            Task task1 = Task.Run(async () => { await 网络操作.是否已经下载完毕Async(); });
            await task1;
            this.TextSchedule = string.Empty;
            this.TextSchedule = "下载完毕,开始解压";
            FuncOutCome unzipOutcome = MyDataFolderOperator.UnZip(MyDataFolderOperator.DownloadFolderPathInAuditProgramFolder);
            if (unzipOutcome.FuncSuccessCode != FuncOutComeCodeType.Success)
            {
                
                this.TextSchedule += $"数据解压出错,请重试!" + Environment.NewLine + unzipOutcome.FuncOutComeInfoArgs + Environment.NewLine;
                return ;
            }

            //开始导入
            MyProgressBar progressBar = new MyProgressBar();
            progressBar.Show();
            var progress = new Progress<int> (value => progressBar.UpdateProgress (value));
            string[] StrArrXlsFiles = Directory.GetFiles(MyDataFolderOperator.DownloadFolderPathInAuditProgramFolder, "*.xls");
            FuncOutCome importOutcome = await Task.Run(() => XlsToSqlite.ExportXlsFilesToSqlite(StrArrXlsFiles, progress));
            if (importOutcome.FuncSuccessCode != FuncOutComeCodeType.Success)
            {
                this.TextSchedule += importOutcome.FuncOutComeInfoArgs;
                await MyMessagebox.ShowAsync("导入出错,请重试",_thisWindow, importOutcome.Icon);
                progressBar.Close();
                return;
            }
            progressBar.Close();
            this.TextSchedule = "导入完成!";
            await MyMessagebox.ShowAsync($"{IntChooseYear}第{IntChooseSeason}季度国网数据已经成功导入到本地数据库!",_thisWindow,Icon.Success,ButtonEnum.Ok);
            }
            catch (Exception ex)
            {
                StaticLogger.SystemError($"国网自动下载出错,错误信息为{ex.Message}");
                StaticLogger.SystemError($"堆栈为{ex.StackTrace},{Environment.NewLine}对象为{ex.Source},{Environment.NewLine}方法为{ex.TargetSite}");

            }
        }
        private async Task ExecuteGetA406Data()
        {
            try
            {
                StaticLogger.SystemInfo("执行下载省网操作");
                MyDataFolderOperator.CreateOrResetDownloadFolder();

                Dictionary<int, int> downYearAndSeason = new Dictionary<int, int>
                {
                    { IntChooseYear, IntChooseSeason }
                };
                bool isGetDataFromNationSuccess = await 网络操作.Get406(this.Str省网账号, this.Str省网密码, this.IntChooseYear,
                    this.IntChooseSeason, MyDataFolderOperator.DownloadFolderPathInAuditProgramFolder);
                if (!isGetDataFromNationSuccess)
                {
                    this.TextSchedule = string.Empty;
                    this.TextSchedule = $"数据下载出现错误,请重试!" + Environment.NewLine;
                    return;
                }

                Task task1 = Task.Run(async () => { await 网络操作.是否已经下载完毕Async(); });
                await task1;
                this.TextSchedule = string.Empty;
                this.TextSchedule = "下载完毕,开始解压";
                FuncOutCome unzipOutcome =
                    MyDataFolderOperator.UnZip(MyDataFolderOperator.DownloadFolderPathInAuditProgramFolder);
                if (unzipOutcome.FuncSuccessCode != FuncOutComeCodeType.Success)
                {

                    this.TextSchedule += $"数据解压出错,请重试!" + Environment.NewLine + unzipOutcome.FuncOutComeInfoArgs +
                                         Environment.NewLine;
                    return;
                }

                //开始导入
                MyProgressBar progressBar = new MyProgressBar();
                progressBar.Show();
                var progress = new Progress<int>(value => progressBar.UpdateProgress(value));
                string[] StrArrXlsFiles =
                    Directory.GetFiles(MyDataFolderOperator.DownloadFolderPathInAuditProgramFolder, "*.xls");
                FuncOutCome importOutcome =
                    await Task.Run(() => XlsToSqlite.ExportXlsFilesToSqlite(StrArrXlsFiles, progress));
                if (importOutcome.FuncSuccessCode != FuncOutComeCodeType.Success)
                {
                    this.TextSchedule += importOutcome.FuncOutComeInfoArgs;
                    await MyMessagebox.ShowAsync("导入出错,请重试", _thisWindow, importOutcome.Icon);
                    progressBar.Close();
                    return;
                }

                progressBar.Close();
                this.TextSchedule = "导入完成!";
                await MyMessagebox.ShowAsync($"{IntChooseYear}第{IntChooseSeason}季度A406数据已经成功导入到本地数据库!", _thisWindow,
                    Icon.Success, ButtonEnum.Ok);
            }
            catch (Exception ex)
            {
                StaticLogger.SystemError($"省网自动下载出错,错误信息为{ex.Message}");
                StaticLogger.SystemError($"堆栈为{ex.StackTrace},{Environment.NewLine}对象为{ex.Source},{Environment.NewLine}方法为{ex.TargetSite}");

            }
        }
        private async Task ExecuteGetDataFromStatsCloud()
        {
            try
            {
                StaticLogger.SystemInfo("执行从统计云下载数据操作");
                string[] Arr表名 = { "209", "210", "211", "212" };
                bool isGetDataFromStatsCloudSuccess = await 网络操作.GetMassInStatsCloud(Str统计云账号, Str统计云密码,
                    MyDataFolderOperator.AuditProgramFolderPath, IntChooseSeason, Arr表名);
                if (isGetDataFromStatsCloudSuccess == true)
                {
                    await MyMessagebox.ShowAsyncInMainWindow("统计云全部导入成功!", Icon.Success);

                }
            }
            catch (Exception ex)
            {
                StaticLogger.SystemError($"统计云自动下载出错,错误信息为{ex.Message}");
                StaticLogger.SystemError($"堆栈为{ex.StackTrace},{Environment.NewLine}对象为{ex.Source},{Environment.NewLine}方法为{ex.TargetSite}");

            }

        }
    }
}
